import React, { PureComponent, memo, useRef, useEffect, useCallback } from 'react'
import ToTopBtn from '../ToTopBtn'
import './index.scss'
const ScrollToTop = memo(function ScrollToTop(props) {
    const {} = props
    const toTopRef = useRef()
    useEffect(() => {
        window.addEventListener('scroll', handleScroll, true)
        return () => {
            window.removeEventListener('scroll', handleScroll, true)
        }
    }, [])
    const handleScroll = useCallback(() => {
        const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
        if (scrollTop >= window.innerHeight) {
            toTopRef.current.style.display = 'block'
        } else {
            toTopRef.current.style.display = 'none'
        }
    })
    const handleClick = useCallback(() => {
        //滚动 高度
        const initialScrollTop = document.documentElement.scrollTop || document.body.scrollTop
        // 计算每次减少的步长
        const step = Math.round(initialScrollTop / 10)
        // 写滚动 方法 用 requestAnimationFrame 调用
        const scroll = () => {
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            window.scrollTo(0, scrollTop - step)
            if (scrollTop > 0) {
                requestAnimationFrame(scroll)
            }
        }
        requestAnimationFrame(scroll)
    })
    return (
        <div
            className="totop"
            ref={toTopRef}
            onClick={() => {
                handleClick()
            }}
        >
            <ToTopBtn />
        </div>
    )
})

export default ScrollToTop
